<?php
/**
 * @desc 微信.APP支付
 * @document https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=9_1
 * @author Vincent
 */

namespace young\payment;

use young\Common;

class WxAppPay extends WxConfig
{
    public function run($data)
    {
        $this->setConfig($data['config']);
        return $this->handle($data['body'], $data['order_sn'], $data['amount'], $data['notify_url']);
    }

    public function handle($body, $orderSn, $amount, $notifyUrl)
    {
        $url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
        $common = [];
        $common['appid'] = $this->appid;
        $common['mch_id'] = $this->mch_id;
        $common['nonce_str'] = Common::rand_string(32);
        $common['sign_type'] = self::SIGN_TYPE;
        $common['body'] = $body;
        $common['out_trade_no'] = $orderSn;
        $common['total_fee'] = $this->formatAmount($amount);
        $common['spbill_create_ip'] = $_SERVER['REMOTE_ADDR'];
        $common['notify_url'] = $notifyUrl;
        $common['trade_type'] = 'APP';
        $common['sign'] = $this->sign($common);
        $xml = Common::arrayToXml($common);
        $result = Common::request_post($url, $xml, 0);
        $result = Common::xmlToArray($result);
        if ($result['return_code'] == 'SUCCESS') {
            $data = [
                'appid' => $result['appid'],
                'partnerid' => $result['mch_id'],
                'prepayid' => $result['prepay_id'],
                'package' => 'Sign=WXPay',
                'noncestr' => $result['nonce_str'],
                'timestamp' => REQUEST_TIME
            ];
            $data['sign'] = $this->sign($data);
            return $data;
        } else {
            throw new \Exception('[code:' . $result['return_code'] . '][msg:' . $result['return_msg'] . ']');
        }
    }
}